//
//  MTWebViewController.m
//  MeToo
//
//  Created by 俊松何 on 2018/7/3.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "MTWebViewController.h"
#import <WebKit/WebKit.h>
#import "RegExCategories.h"

@interface MTWebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property(nonatomic,strong) WKWebView *wkwebView;
@property(nonatomic,strong) UIProgressView *progressView;
@property (nonatomic ,strong)WKUserContentController * userCC;



@end

@implementation MTWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeUI];
}
-(void)makeUI
{
    
//     self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.navigationController.navigationBar lt_setBackgroundColor:navgationBarColor];
    self.navigationController.navigationBar.backgroundColor = navgationBarColor;
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    _wkwebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    _wkwebView.scrollView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
    
    _wkwebView.navigationDelegate = self;
    _wkwebView.UIDelegate = self;
    _progressView = [[UIProgressView alloc] init];
    _progressView.progressTintColor = mainTintColor;
    [self.view addSubview:_wkwebView];
    [self.view addSubview:_progressView];
   
    
    [_wkwebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.bottom.mas_equalTo(self.view.mas_bottom);
    }];

    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.height.mas_equalTo(@(2));
    }];
    NSURL *url = [[NSURL alloc] initWithString:_url];
    NSURLRequest *requst = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [_wkwebView loadRequest:requst];
    [_wkwebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [_wkwebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:self.backImage] forState:UIControlStateNormal];
    [but setImage:[UIImage imageNamed:self.backImage] forState:UIControlStateHighlighted];
    [but addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    but.frame = CGRectMake(0, 0, 40, 40);
    but.contentMode = UIViewContentModeLeft;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:but];
    self.navigationItem.leftMargin = 0;
    
    self.userCC = config.userContentController;
    [self.userCC addScriptMessageHandler:self name:@"callFunc"];
 
    
    
}

-(void)goBack
{
    if(self.navigationController.viewControllers.count > 1)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }else
    {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    // 返回页面的时候取消监听
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        self.progressView.progress = self.wkwebView.estimatedProgress;
        if (self.progressView.progress == 1)
        {
            self.progressView.hidden = YES;
        }else
        {
            self.progressView.hidden = NO;
        }
    }else if ([keyPath isEqualToString:@"title"])
    {
        self.title = self.wkwebView.title;
    }
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *url = navigationAction.request.URL;
    NSString *urlString = (url) ? url.absoluteString : @"";
    
    // iTunes: App Store link
    if ([urlString isMatch:RX(@"\\/\\/itunes\\.apple\\.com\\/")]) {
        
        [[UIApplication sharedApplication] openURL:url];
        //        [self.navigationController popViewControllerAnimated:NO];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    // Protocol/URL-Scheme without http(s)
    else if (![urlString isMatch:[@"^https?:\\/\\/." toRxIgnoreCase:YES]]) {
        
        [[UIApplication sharedApplication] openURL:url];
        //        [self.navigationController popViewControllerAnimated:NO];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark  WKScriptMessageHandler delegate
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"callFunc"]) {
        NSString * jump = message.body;
        if([jump  isEqualToString:@"MT://authentication/commit"])
        {
            if(_isShow)
            {
                [self.navigationController popViewControllerAnimated:YES];
            }else{
//                [MBProgressHUD showSuccess:@"提交成功，等待审核" toView:nil];
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            }
        }
    }
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}





@end
